﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using Facebook.Web.FbmlControls;
using Facebook.Web;

public partial class _Default : CanvasFBMLBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }


    //Handles stuff before the page loads
    protected void Page_PreInit(object sender, EventArgs e)
    {
        try
        {
            string uid = this.Api.Users.GetInfo().uid.ToString();
            Session["uid"] = uid;               //store the uid
            Session.Timeout = 60;               //set the timeout to an hour

            //connect to the database
            using (SqlConnection dbconn = new SqlConnection(Lutefisk.CONNECTION_STRING))
            {
                dbconn.Open();                  //create a connection

                //Look if the user is in the database
                string searchString = "SELECT * FROM musicians WHERE UID=" + uid + ";";
                using (SqlCommand sql = new SqlCommand(searchString, dbconn))
                {
                    using (SqlDataReader reader = sql.ExecuteReader())
                    {
                        if (!reader.HasRows)   //if datareader is empty, the user is not present
                        {
                            //redirect user if they aren't present in the system
                            Lutefisk.DirectPage(this.Page, "Form");
                        }
                        else
                        {
                            Lutefisk.DirectPage(this.Page, "Profile");
                        }
                    }
                }
            }
        }
        catch
        {
           // First login; ASPX FBML controls will catch this and ask for authentification. 
        }
    } 
        
}